package com.xu.modules.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.qiniu.common.QiniuException;
import com.xu.common.domain.MyResult;
import com.xu.common.exception.MyException;
import com.xu.common.qiNiu.QiNiuUtil;
import com.xu.common.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

/**
 * 文件上传控制层
 *
 * @author xu
 * 2022/7/22 16:45
 */
@RestController
@RequestMapping("/upload")
@RequiredArgsConstructor
@Slf4j
public class UploadController {

    private final QiNiuUtil qiNiuUtil;

    @PostMapping("/upload")
    public MyResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            String prefixFileName = qiNiuUtil.uploadFile(file.getBytes(), FileUtil.getRandomFileName(Objects.requireNonNull(file.getOriginalFilename())));
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("prefixFileName",prefixFileName);
            return MyResult.ok(jsonObject);
        }catch (IOException ioException){
            throw new MyException("上传失败");
        }

    }

    @DeleteMapping("/delete/{fileId}")
    public void delete(@PathVariable String fileId){
        try {
            if(fileId.equals("1")){
                qiNiuUtil.deleteFile("http://cdn.xuwang.info/a5b5755eca1148218248860605d355d0.png");
            }

        } catch (QiniuException e) {
            e.printStackTrace();
            throw new MyException("删除失败");
        }
    }
}
